'use strict';

module.exports = core;
 
const path = require('path')
const semver = require('semver')
const colors = require('colors')
const userHome = require('user-home')
const command = require('commander')

const constant = require('./const')
const pkg = require('../package.json')

// 子包
const log = require('@xqc-ink-cli/log') 
const exec = require('@xqc-ink-cli/exec')

let pathExists; 

const program = new command.Command()

async function core() {
   try {
      pathExists = (await import('path-exists'))
      prepare()
      registerCommander()
   }
   catch (e) {
      log.error(e.message)
   }
}

async function prepare(){
   checkPkgVerison()
   checkRoot() 
   checkUserHome() 
   checkEnv()
   await checkGlobalUpdate()
}

function registerCommander(){
  
   program
      .name(Object.keys(pkg.bin)[0])
      .usage('<commamd> [options]')
      .version(pkg.version)
      .option('-d, --debug [p]', '是否开启调试模式', true)
      .option('-tp, --targetPath <targetPath>', '是否指定本地调试文件路径', '');
   
   // ！注册一个Commands: init test-project --froce 指令 
   program
      .command('init [projectName]')
      .option('-f, --force [force]', '是否强制初始化')
      .action(exec);
      
    
   // ! 指定命令的监听:开启debug模式
   program.on('option:debug', function(debug)  {
      !debug ? process.env.LOG_LEVEL = 'verbose' : process.env.LOG_LEVEL = 'info' 
      log.level = process.env.LOG_LEVEL
   });
    
   // ! 指定:targetPath
   program.on('option:targetPath', function(targetPath)  {
     process.env.CLI_TARGET_PATH = targetPath
   })
   
   // 未知命令的监听
   program.on('command:*', (obj) => {
      const availableCommands = program.commands.map(cmd => cmd.name)
      console.log(colors.red('未知命令：' + obj[0 ], availableCommands))
      if(availableCommands.length > 0) console.log(colors.red('可用命令：' + availableCommands.join(',')));
   }); 

   program.parse(process.argv);
}


async function checkGlobalUpdate(){
   // 1. 获取当前版本号和模块名
   const currentVersion = pkg.version
   const npmName = pkg.name
   // 2. 调用npm api 获取所有版本号
   const lastVersion = await require('@xqc-ink-cli/get-npm-info').getNpmSemverVersion(currentVersion, npmName)
   if(lastVersion && semver.gt(lastVersion, currentVersion)){
      log.warn(colors.yellow, `请手动更新 ${npmName}, 当前版本：${currentVersion}, 最新版本：${lastVersion}, 更新命名：npm instal -g ${npmName}`)
   }
   // 3. 提取所有版本号, 对比哪些版本号是大于当前版本号的
   // 4. 获取最新的版本号, 提醒用户更新到该版本
}

function checkEnv (){
   const dotenv = require('dotenv')
   const dotenvPath = path.resolve(userHome, '.env')
   if(pathExists.pathExistsSync(dotenvPath)){
      dotenv.config({
         path: dotenvPath
      })  
   }
   createDefaultConfig()
}

function createDefaultConfig(){
   const cliConfig = {
      home: userHome
   }
   /** 
    * CLI_HOME 是通过编写.env写入的
    * CLI_HOME=.xqc-ink-cli
    *  */ 
   if(process.env.CLI_HOME){
      cliConfig['cliHome'] = path.join(userHome, process.env.CLI_HOME)
   }
   else{
      cliConfig['cliHome'] = path.join(userHome, constant.DEFAULT_CLI_HOME)
   }
   // 脚手架主目录
   process.env.CLI_HOME_PATH = cliConfig['cliHome'] 
}

async function checkUserHome(){
   if(!userHome || !pathExists.pathExistsSync(userHome)){
      throw new Error(colors.red('当前登录主目录文件不存在!'));
   }
}

/**
 * root-check
 * 检查当前用户是否root账号登录
 * 当为是的情况会帮我们降级处理 downgrade the permission
 */
async function checkRoot(){ 
   (await import('root-check')).default()
   // console.log(process.getuid())
}

function checkPkgVerison(){
   log.sucess('cli', pkg.version)
}